#include <func.h>
#include "head.h"
//服务端接收客户端发来的文件
//结构体之后放到头文件里去

/**/
int upload(MYSQL *db, char* argv, char* curPath, int netFd, int curPathId, char *userName){
    //puts file
    //pwd /usr1

    char arr[100] = "";
    strcpy(arr, argv);
    char* command = strtok(arr, " ");
    char* fileName = strtok(NULL, " ");
    //得到文件的MD5码
    int dataLength;
    char MD[100] = {0};
    recvn(netFd, &dataLength, sizeof(int));
    recvn(netFd, &MD, dataLength);
    // printf("MD = %s\n", MD);
    char realPath[200] = {0};
    sprintf(realPath, "%s%s%s%s%s", ".", "/", FILEPATH, "/", MD);
    // puts(realPath);
    int fd = open(realPath, O_RDWR|O_CREAT|O_EXCL, 0666);
    if(fd == -1){//服务器上已存在该文件，秒传
        send(netFd, "2", 1, MSG_NOSIGNAL);
    }
    else{
        send(netFd, "0", 1, MSG_NOSIGNAL);

        // fd = open(realPath, O_RDWR|O_CREAT, 0666);
        int fileSize;
        recv(netFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
        recv(netFd, &fileSize, sizeof(fileSize), MSG_WAITALL); 
        printf("fileSize = %d\n", fileSize);
        ftruncate(fd, fileSize);
        char *p = (char *)mmap(NULL, fileSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        recvn(netFd, p, fileSize);
        munmap(p, fileSize);
    }

    //在数据库中记录
    char filePath[200] = {0};
    sprintf(filePath, "%s%s%s", curPath, "/", fileName);
    // puts(filePath);
    char sqlCommand[1024] = {0};
    sprintf(sqlCommand, "insert into catalog (file_name, usr_name, pre_id, md5) values ('%s', '%s', %d, '%s');", filePath, userName, curPathId, MD);
    // puts(sqlCommand);
    int qret = mysql_query(db, sqlCommand);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        return -1;
    }

    close(fd);
    return 0;
}